package com.itheima.service.system.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.system.DeptDao;
import com.itheima.dao.system.UserDao;
import com.itheima.domain.system.Dept;
import com.itheima.domain.system.User;
import com.itheima.service.system.UserService;
import com.itheima.utils.MD5Util;
import com.itheima.utils.MapperUtils;
import com.itheima.utils.UUIDUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class UserServiceImpl implements UserService {
    @Override
    public PageInfo<User> pageQuery(Integer pageNum, Integer pageSize) throws Exception {
        SqlSession sqlSession = MapperUtils.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);

        PageHelper.startPage(pageNum,pageSize);
        List<User> list = userDao.findAll();
        PageInfo<User> pageInfo = new PageInfo<>(list);

        return pageInfo;
    }

    @Override
    public User findById(String id) throws Exception {
        SqlSession sqlSession = MapperUtils.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User byId = userDao.findById(id);
        return byId;
    }

    @Override
    public void update(User user) throws Exception {
        SqlSession sqlSession = MapperUtils.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        userDao.update(user);
        sqlSession.commit();
    }

    @Override
    public void save(User user) throws Exception {
        SqlSession sqlSession = MapperUtils.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        user.setId(UUIDUtil.getSimpleUUID());
        user.setPassword(MD5Util.md5(user.getPassword()));
        userDao.save(user);
        sqlSession.commit();
    }

    @Override
    public void delete(String... ids) throws Exception {
        SqlSession sqlSession = MapperUtils.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        for (String id : ids) {
            userDao.delete(id);
        }
        sqlSession.commit();
    }
}
